package com.example.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.crm.entity.Contract;
import com.example.crm.mapper.ContractMapper;
import com.example.crm.service.ContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 合同服务实现类
 */
@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements ContractService {

    @Autowired
    private ContractMapper contractMapper;

    @Override
    public IPage<Contract> listContractsByPage(Map<String, Object> params) {
        int pageNum = params.get("page") == null ? 1 : Integer.parseInt(params.get("page").toString());
        int pageSize = params.get("limit") == null ? 10 : Integer.parseInt(params.get("limit").toString());
        
        Page<Contract> page = new Page<>(pageNum, pageSize);
        
        QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
        
        // 客户ID筛选
        if (params.containsKey("customerId") && params.get("customerId") != null) {
            queryWrapper.eq("customer_id", params.get("customerId"));
        }
        
        // 合同编号筛选
        if (params.containsKey("contractNo") && !StringUtils.isEmpty(params.get("contractNo"))) {
            queryWrapper.like("contract_no", params.get("contractNo"));
        }
        
        // 状态筛选
        if (params.containsKey("status") && params.get("status") != null) {
            queryWrapper.eq("status", params.get("status"));
        }
        
        // 创建时间范围筛选
        if (params.containsKey("startDate") && !StringUtils.isEmpty(params.get("startDate"))) {
            queryWrapper.ge("create_time", params.get("startDate"));
        }
        if (params.containsKey("endDate") && !StringUtils.isEmpty(params.get("endDate"))) {
            queryWrapper.le("create_time", params.get("endDate"));
        }
        
        // 默认按创建时间倒序
        queryWrapper.orderByDesc("create_time");
        
        return page(page, queryWrapper);
    }

    @Override
    public Contract getContractDetail(Long id) {
        return getById(id);
    }

    @Override
    public List<Contract> getContractsByCustomerId(Long customerId) {
        return contractMapper.selectByCustomerId(customerId);
    }

    @Override
    public List<Contract> getContractsByOpportunityId(Long opportunityId) {
        LambdaQueryWrapper<Contract> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Contract::getOpportunityId, opportunityId)
                    .orderByDesc(Contract::getCreateTime);
        return list(queryWrapper);
    }

    @Override
    public Map<String, Object> getContractStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        // 1. 统计合同总数
        result.put("totalContracts", count());
        
        // 2. 统计合同总金额
        QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("IFNULL(SUM(amount), 0) as totalAmount");
        Map<String, Object> amountMap = getMap(queryWrapper);
        result.put("totalAmount", amountMap.get("totalAmount"));
        
        // 3. 获取合同状态分布
        result.put("statusDistribution", getContractStatusDistribution());
        
        // 4. 获取本月数据
        result.put("newContractsThisMonth", countNewContractsThisMonth());
        result.put("amountThisMonth", sumContractAmountThisMonth());
        
        return result;
    }

    @Override
    public Map<String, Object> getContractStatusDistribution() {
        // 将List<Map<String, Object>>转换为一个统一的Map
        List<Map<String, Object>> statusList = contractMapper.countGroupByStatus();
        Map<String, Object> result = new HashMap<>();
        
        for (Map<String, Object> statusMap : statusList) {
            Integer status = (Integer) statusMap.get("status");
            Long count = ((Number) statusMap.get("count")).longValue();
            
            // 将状态码转换为状态名称
            String statusName;
            switch (status) {
                case 0:
                    statusName = "草稿";
                    break;
                case 1:
                    statusName = "审核中";
                    break;
                case 2:
                    statusName = "执行中";
                    break;
                case 3:
                    statusName = "完成";
                    break;
                case 4:
                    statusName = "取消";
                    break;
                default:
                    statusName = "未知状态";
            }
            
            result.put(statusName, count);
        }
        
        return result;
    }

    @Override
    public List<Map<String, Object>> getContractAmountTrend(Integer months) {
        if (months == null || months <= 0) {
            months = 6; // 默认6个月
        }
        // ContractMapper中的monthlySalesLast6Months方法不接受参数
        return contractMapper.monthlySalesLast6Months();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addContract(Contract contract) {
        if (contract.getContractNo() == null || contract.getContractNo().isEmpty()) {
            // 生成合同编号
            contract.setContractNo(generateContractNo());
        }
        
        if (contract.getCreateTime() == null) {
            contract.setCreateTime(LocalDateTime.now());
        }
        
        return save(contract);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateContract(Contract contract) {
        Contract existingContract = getById(contract.getId());
        if (existingContract == null) {
            return false;
        }
        
        contract.setUpdateTime(LocalDateTime.now());
        return updateById(contract);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateContractStatus(Long id, Integer status) {
        Contract contract = new Contract();
        contract.setId(id);
        contract.setStatus(status);
        contract.setUpdateTime(LocalDateTime.now());
        return updateById(contract);
    }

    @Override
    public Long countNewContractsThisMonth() {
        // 直接使用mapper中的方法
        return contractMapper.countNewContractsThisMonth();
    }

    @Override
    public BigDecimal sumContractAmountThisMonth() {
        // 直接使用mapper中的方法
        return contractMapper.sumNewContractAmountThisMonth();
    }
    
    /**
     * 生成合同编号
     */
    private String generateContractNo() {
        String prefix = "HT";
        String datePart = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        
        // 获取当日已有合同数量
        String datePrefix = prefix + datePart;
        QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
        queryWrapper.likeRight("contract_no", datePrefix);
        long countValue = count(queryWrapper);
        int countInt = (int) (countValue + 1);
        
        // 格式化编号，确保4位序号
        String serialNumber = String.format("%04d", countInt);
        
        return datePrefix + serialNumber;
    }
} 